import axios from 'axios'
import type { AxiosRequestConfig, AxiosInstance, AxiosRequestHeaders, AxiosResponse, AxiosError } from 'axios'
import { ElMessageBox, ElMessage } from 'element-plus'
import route from '@/router/index'
import qs from 'qs'

// 创建一个axios实例
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_BASE_API, // 向请求url前拼接
  withCredentials: true, // 当跨域请求时发送cookie
  timeout: 10000, // 	请求超时毫秒
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})

let isConfirm = false //防止打开多个确认框

// 添加请求拦截器
service.interceptors.request.use(function (config: AxiosRequestConfig) {  // 在发送请求之前做些什么
  const token: string = sessionStorage.getItem('access_token') || '';
  (config.headers as AxiosRequestHeaders)['accessToken'] = token
  // console.log(config.headers['accessToken']);

  // 额外的参数
  const extra_parameter = {}
  // 参数处理
  if ((config.method as string).toLowerCase() === 'post') {
    config.data = qs.stringify({ ...config.data, ...extra_parameter }) // 这里必须使用qs库进行转换
  } else if ((config.method as string).toLowerCase() === 'get') {
    config.params = { ...config.params, ...extra_parameter }
  }

  return config;
}, function (error: AxiosError) { // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
service.interceptors.response.use(function (response: AxiosResponse<any>) { // 对响应数据做点什么
  const res = response.data
  if (res.code === 0) {
    // 正常状态
    return res
  } else if (res.code === -1 && route.currentRoute.value.path !== '/login') {
    // 重新登陆
    if (isConfirm === false) {
      isConfirm = true
      ElMessageBox.confirm('您已经登出，请重新登录以继续使用', '确认注销', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        showCancelButton: false,
        showClose: false,
        type: 'warning'
      }).then(() => {
        sessionStorage.removeItem('access_token')
        route.push({ path: `/login?redirect=${location.href.split('#')[1]}` })
      }).finally(() => {
        isConfirm = false
      })
    }
    return res
  } else {
    // 其它异常
    ElMessage({
      message: res.msg || '服务器出错了，手动刷新页面试试吧~',
      type: 'error',
      duration: 3000
    })
    return res
  }
}, function (error: AxiosError) { // 对响应错误做点什么
  let err_msg = ''
  if (error.message.indexOf('timeout') !== -1) {
    err_msg = '请求超时了，请手动刷新页面重试~'
  } else if (error.message.indexOf('Request failed with status code') !== -1) {
    err_msg = error.message.replace(/Request failed with status code/g, '请求失败！状态码：')
  } else {
    err_msg = error.message
  }
  ElMessage({
    message: err_msg,
    type: 'error',
    duration: 3000
  })
  return Promise.reject(error)
});

export const get = (url: string, params: AnyObject = {}, custom: AnyObject = {}) => service({ url, method: 'get', params, ...custom })
export const post = (url: string, data: AnyObject = {}, custom: AnyObject = {}) => service({ url, method: 'post', data, ...custom })
